package com.authine.cloudpivot.ext.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.engine.api.facade.BizObjectFacade;
import com.authine.cloudpivot.engine.api.facade.OrganizationFacade;
import com.authine.cloudpivot.engine.api.model.organization.DepartmentUserModel;
import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.engine.api.model.runtime.*;
import com.authine.cloudpivot.engine.api.model.workflow.WorkflowTemplateHeaderModel;
import com.authine.cloudpivot.engine.component.query.api.Page;
import com.authine.cloudpivot.engine.component.query.api.helper.PageableImpl;
import com.authine.cloudpivot.engine.enums.ErrCode;
import com.authine.cloudpivot.engine.enums.status.UserStatus;
import com.authine.cloudpivot.engine.enums.type.DefaultPropertyType;
import com.authine.cloudpivot.engine.enums.type.ProcessRunMode;
import com.authine.cloudpivot.engine.enums.type.UnitType;
import com.authine.cloudpivot.engine.workflow.model.activity.ParticipantActivity;
import com.authine.cloudpivot.ext.domain.BizAttachment;
import com.authine.cloudpivot.ext.domain.Certificate;
import com.authine.cloudpivot.ext.mapper.BizAttachmentMapper;
import com.authine.cloudpivot.ext.mapper.CertificateMapper;
import com.authine.cloudpivot.web.api.controller.runtime.FormRuntimeController;
import com.authine.cloudpivot.web.api.view.ResponseResult;
import com.authine.cloudpivot.web.api.view.StartOtherFlowObject;
import com.authine.cloudpivot.web.api.view.bizservice.BizServiceMethodVO;
import com.authine.cloudpivot.web.api.view.runtime.BizObjectVO;
import com.authine.cloudpivot.web.api.view.runtime.FormSaveVO;
import com.authine.cloudpivot.web.api.view.runtime.StartWorkflowDataVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/public/bizrule")
@Slf4j
public class FZVController extends FormRuntimeController {

    @Autowired
    private BizAttachmentMapper bizAttachmentMapper;
    @Autowired
    private CertificateMapper certificateMapper;

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

    Object certificate = null;
    /**
     * 自定义流程获取参与者接口
     *
     * @param createUser
     * @return
     */
    @PostMapping("/getUserId")
    public String getUserId(String createUser) {
        log.info("getUserId:{}", createUser);
        String createId = getIdFromSelectionValue(createUser);

        log.info("createId:{}", createId);

        if (!StringUtils.isEmpty(createId)) {

            return getLeaderId(createId);
        }
        return "";
    }



    /**
     * erp 调用发起流程接口
     */
    @PostMapping("/startOtherFlow")
    public ResponseResult<String> startOtherFlow(@RequestBody StartOtherFlowObject StartOtherFlowObject) throws ParseException {
        //log.info("发起流程参数：userNo:"+userNo+" workflowCode:"+workflowCode+" data:"+ data);
        log.info("发起流程参数：StartOtherFlowObject:" + StartOtherFlowObject);

        //通过erp员工编号获取云枢对应的员工
        //String userName = getUserNameByErp();
        StartWorkflowDataVO startWorkflowDataVO = new StartWorkflowDataVO();
        startWorkflowDataVO.setUsername(StartOtherFlowObject.getUserNo());
        startWorkflowDataVO.setWorkflowCode(StartOtherFlowObject.getWorkflowCode());

        Map<String, Object> data = StartOtherFlowObject.getData();
        data.remove("id");
        Object scopeSupply1 = data.get("Sheet1635220528547");
        Object certificate1 = data.get("Sheet1634799789547");
        //供货范围2
        Object scopeSupply2 = data.get("Sheet1635220674576");
        //证书2
        Object certificate2 = data.get("Sheet1635220677003");
        //移除证书数据
        data.remove("Sheet1634799789547");
        data.remove("Sheet1635220677003");
        data.remove("Sheet1634872344354");
        if(null != scopeSupply1){
            log.info("供货范围1>>>>>>>>>>>>>>>>>>{}",scopeSupply1);
            rmId(scopeSupply1);
            data.put("Sheet1635216736286",scopeSupply1);
        }else if(null != scopeSupply2){
            log.info("供货范围2>>>>>>>>>>>>>>>>>>{}",scopeSupply2);
            rmId(scopeSupply2);
            data.put("Sheet1635216736286",scopeSupply2);
        }else{
            data.remove("Sheet1635216736286");
        }
        if(null != certificate2){
            certificate =certificate2;
        }else if(null != certificate1){
            certificate =certificate1;
        }
        /*if(null != certificate1){
            log.info("证书1>>>>>>>>>>>>>>>>>>{}",certificate1);
            List<Map<String, Object>> list = (List<Map<String, Object>>) certificate1;
            changeDate(list);
            data.put("Sheet1634872344354",list);
        }else if(null != certificate2){
            log.info("证书2>>>>>>>>>>>>>>>>>>{}",certificate2);
            List<Map<String, Object>> list = (List<Map<String, Object>>) certificate2;
            log.info("证书list>>>>>>>>>>>>>>>>>>{}",list);
            changeDate(list);
            data.put("Sheet1634872344354",list);
        }*/

        if(null != data.get("schemaCode")){
            log.info("schemaCode>>>>>>>>>>>>>>>>>>{}",data.get("schemaCode"));
            String schemaCode = String.valueOf(data.get("schemaCode")).replaceAll("supplier", "changshangxinzeng").replaceAll("allSupplier", "changshangxinzeng");
            data.put("schemaCode",schemaCode);
        }
        if(null != data.get("sheetCode")){
            log.info("sheetCode>>>>>>>>>>>>>>>>>>{}",data.get("sheetCode"));
            String sheetCode = String.valueOf(data.get("sheetCode")).replaceAll("supplier", "changshangxinzeng").replaceAll("allSupplier", "changshangxinzeng");
            data.put("sheetCode",sheetCode);
        }
        //组装供应商选人控件
        String no = String.valueOf(StartOtherFlowObject.getData().get("PMC01"));
        UserModel userModel = getOrganizationFacade().getUserByUsername(no);
        if (userModel != null) {
            List<SelectionValue> list = new ArrayList<>();
            SelectionValue selectionValue = new SelectionValue();
            selectionValue.setType(UnitType.USER);
            selectionValue.setId(userModel.getId());
            selectionValue.setName(userModel.getName());
            list.add(selectionValue);
            data.put("user",JSONObject.toJSONString(selectionValue));
        }
        startWorkflowDataVO.setData(data);

        return this.startWorkflow(startWorkflowDataVO);
    }
    private void rmId(Object certificate){
        List<Map<String, Object>> list = (List<Map<String, Object>>) certificate;
        for(Map<String, Object> map :list){
            map.remove("id");
        }
    }
    private List<Map<String, Object>>  changeDate(List<Map<String, Object>> list) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        for(Map<String, Object> map :list){
            if(null != map.get("dateStart")){
                Date date = format.parse(String.valueOf(map.get("dateStart")));
                map.put("dateStart",date);
            }
            if(null != map.get("dateEnd")){
                Date date2 = format.parse(String.valueOf(map.get("dateEnd")));
                map.put("dateEnd",date2);
            }
/*
            if(null != map.get("data")){
                log.info("证书>>>>>>>>>>>>>>>>>>{}",map.get("data"));
                String data = String.valueOf(map.get("data")).replaceAll("supplier", "changshangxinzeng").replaceAll("allSupplier", "changshangxinzeng");
                map.put("data",data);
            }*/

        }
        return list;
    }
    /**
     * erp 调用发起流程接口
     */
    @GetMapping("/startFlowNoMatching")
    public ResponseResult<String> startFlowNoMatching(String userNo, String workflowCode, String unionId, String shortText0, String shortText1) {

        log.info("发起流程参数：userNo:" + userNo + " workflowCode:" + workflowCode + " unionId:" + unionId);

        HashMap<String, Object> data = new HashMap<>();

        data.put("unionId", unionId);
        data.put("shortText0", shortText0);

        data.put("shortText1", shortText1);


        StartWorkflowDataVO startWorkflowDataVO = new StartWorkflowDataVO();
        startWorkflowDataVO.setUsername(userNo);
        startWorkflowDataVO.setWorkflowCode(workflowCode);
        startWorkflowDataVO.setData(data);

        return this.startWorkflow(startWorkflowDataVO);
    }
    /**
     * erp 调用发起流程接口
     */
    @GetMapping("/startFlow")
    public ResponseResult<String> startFlow(String userNo, String workflowCode, String unionId, String shortText0, String shortText1) {

        log.info("发起流程参数：userNo:" + userNo + " workflowCode:" + workflowCode + " unionId:" + unionId);

        //通过erp员工编号获取云枢对应的员工
        String userName = getUserNameByErp(userNo);

        HashMap<String, Object> data = new HashMap<>();

        data.put("unionId", unionId);
        data.put("shortText0", shortText0);

        data.put("shortText1", shortText1);


        StartWorkflowDataVO startWorkflowDataVO = new StartWorkflowDataVO();
        startWorkflowDataVO.setUsername(userName);
        startWorkflowDataVO.setWorkflowCode(workflowCode);
        startWorkflowDataVO.setData(data);

        return this.startWorkflow(startWorkflowDataVO);
    }

    @GetMapping("/getObject")
    public Object getObject(String userId) {

        return null;
    }

    @PostMapping("/service_test")
    public ResponseResult<Map<String, Object>> testBizServiceMethod(@RequestBody BizServiceMethodVO bizServiceMethodVO) {
        Map<String, Object> map = new HashMap<>();
        map = getBizServiceFacade().testBizServiceMethod(bizServiceMethodVO.getServiceCode(), bizServiceMethodVO.getCode(), bizServiceMethodVO.getTestInputParametersMap());
        return getOkResponseResult(map, "运行业务集成方法成功");
    }


    public String getIdFromSelectionValue(String creteaUser) {
        try {
            String[] split = creteaUser.split(",");
            for (String a : split) {
                if (a.trim().startsWith("id")) {
                    String[] id = a.split("=");
                    return id[1];
                }
            }
        } catch (Exception e) {
            log.error("解析选人控件异常", e);
        }
        return "";
    }

    public String getLeaderId(String userId) {
        BizObjectQueryModel queryModel = new BizObjectQueryModel();
        queryModel.setSchemaCode("zhuguanpeizhi");
        queryModel.setQueryCode("zhuguanpeizhi");
        queryModel.setPageable(new PageableImpl(0, 100));
        Page<BizObjectModel> modelPage = getBizObjectFacade().queryBizObjects(queryModel);

        if (modelPage != null && !CollectionUtils.isEmpty(modelPage.getContent())) {
            List<? extends BizObjectModel> content = modelPage.getContent();
            if (!CollectionUtils.isEmpty(content)) {
                for (BizObjectModel model : content) {
                    ArrayList<SelectionValue> users = (ArrayList<SelectionValue>) model.getData().get("StaffSelector1600399320592");
                    if (!CollectionUtils.isEmpty(users)) {
                        for (SelectionValue user : users) {
                            String id = user.getId();
                            if (userId.equals(id)) {
                                ArrayList<SelectionValue> leaderUser = (ArrayList<SelectionValue>) model.getData().get("StaffSelector1600399280115");
                                if (!CollectionUtils.isEmpty(leaderUser)) {
                                    return leaderUser.get(0).getId();
                                }
                            }
                        }

                    }
                }
            }
        }
        return "";
    }

    public ResponseResult<String> startWorkflow(StartWorkflowDataVO bizObject) {
        if (bizObject == null) {
            return getErrResponseResult("", ErrCode.SYS_PARAMETER_EMPTY.getErrCode(), "参数为空");
        }
        String workflowCode = bizObject.getWorkflowCode();
        String username = bizObject.getUsername();
        boolean finishStart = bizObject.getFinishStart();
        Map<String, Object> data = bizObject.getData();
        log.info("start workflow: workflowCode = {}, username = {}, formData = {}", workflowCode, username,
                JSON.toJSONString(data));

        UserModel userModel = getOrganizationFacade().getUserByUserNameAndCorpId(username, getMainCorpId());
        if (userModel == null) {
            return getErrResponseResult(username, ErrCode.ORG_USER_NONEXISTENT.getErrCode(), "用户不存在");
        }
        WorkflowTemplateHeaderModel headerModel = getAppManagementFacade().getWorkflowTemplateHeader(workflowCode);
        if (headerModel == null) {
            return getErrResponseResult(workflowCode, ErrCode.WORKFLOW_NOT_EXIST.getErrCode(), "流程不存在");
        }

        ParticipantActivity participantActivity = getAppManagementFacade().getOriginateActivity(workflowCode, null);
        if (participantActivity == null) {
            return getErrResponseResult(workflowCode, ErrCode.WORKFLOW_NO_START_ACTIVITY.getErrCode(), "没有找到流程发起节点");
        }

        BizObjectModel bo = new BizObjectModel(headerModel.getSchemaCode(), data, false);
        log.info("new BizObjectModel");
        bo.setFormCode(participantActivity.getSheetCode());

        String workflowInstanceId = "";
        if (!finishStart) {
            BizObjectVO bov = new BizObjectVO();
            bov.setBizObject(bo);
            bov.setWorkflowCode(workflowCode);

            if (org.apache.commons.lang3.StringUtils.isBlank(bov.getBizObject().getString(DefaultPropertyType.OWNER_DEPT_ID.getCode()))) {
                bov.getBizObject().setOwnerDeptId(userModel.getDepartmentId());
            }
            log.info("saveWorkflow before");
            FormSaveVO resultVO = null;
            try {
                resultVO = saveWorkflow(userModel.getId(), userModel.getId(), bov);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            log.info("saveWorkflow end");
            if (resultVO == null) {
                return getErrResponseResult(workflowCode, ErrCode.WORKFLOW_NOT_EXIST.getErrCode(), "流程发起失败1");
            }
            //workflowInstanceId = resultVO.getWorkItem().getInstanceId();
        }
        return getOkResponseResult("ok", "");
    }


    private FormSaveVO saveWorkflow(String userId, String ownerId, BizObjectVO bizObjectVO) throws ParseException {
        String workflowCode = bizObjectVO.getWorkflowCode();

        validateNotEmpty(workflowCode, ErrCode.WORKFLOW_CODE_EMPTY.getErrMsg());
        FormSaveVO formSave = new FormSaveVO();
        BizObjectModel objectModel = bizObjectVO.getBizObject();
        String workflowInstanceId = objectModel.getWorkflowInstanceId();

        //objectModel.setFormCode(getFormCode(workflowInstanceId, workflowCode));
        String objectId = objectModel.getId();

        //是否是发起流程
        boolean isStartWf = org.apache.commons.lang3.StringUtils.isEmpty(workflowInstanceId);

        // 发起流程，防止重复提交
        if (isStartWf) {
            objectModel.setWorkflowInstanceId(UUID.randomUUID().toString().replaceAll("-", ""));
            //校验码去掉
            //this.verifyReplay(bizObjectVO.getReplayToken());
        }

//        if (bizObjectVO.getSaveBizObject()) {
//            if (log.isDebugEnabled()) {
//                log.debug("setSaveBizObject userId = {}, bizObject = {},", userId,
//                        JSONObject.toJSONString(objectModel));
//            }
//            objectId = saveBizObject(userId, objectModel);
//        }
        formSave.setObjectId(objectId);
        WorkItemModel workItem;

        if (!isStartWf) {//暂存
            objectId = temporaryStore(userId, bizObjectVO.getWorkItemId(), objectModel, bizObjectVO.getApproval());
            bizObjectVO.setWorkflowInstanceId(workflowInstanceId);
            workItem = getWorkOrCirculateItem(bizObjectVO.getWorkItemId());
        } else {
            // 发起流程
            String departmentId = objectModel.getString(DefaultPropertyType.OWNER_DEPT_ID.getCode());
            log.info("workflowInstanceId  before");
            workflowInstanceId = startWorkflow(departmentId, userId, null, objectModel, bizObjectVO.getApproval(), workflowCode, Boolean.TRUE, false, ProcessRunMode.MANUAL);
            if(null != certificate){
                log.info("certificate={}",certificate);
                buildFile(workflowInstanceId);
                certificate = null;
            }
            log.info("workflowInstanceId  end");
            workItem = getWorkItemByInstanceIdAndUserId(userId, workflowInstanceId);
            formSave.setWorkflowInstanceId(workflowInstanceId);
        }

        if (workItem != null) {
            if (log.isDebugEnabled()) {
                log.debug("workflowCode = {}, instanceId = {},", workflowCode, workflowInstanceId);
            }

            //saveComment(userId, objectId, objectModel.getSchemaCode(), bizObjectVO.getApproval(), FormActionType.TS);

            formSave.setWorkItem(workItem);

            //BizObjectCreatedModel bizObjectCreated = getBizObjectFacade().getBizObject(userId, objectModel.getSchemaCode(), objectId);
            //writeOperationLogForBizObject(workItem.getInstanceId(), workItem.getId(), workItem.getActivityCode(), OperationType.TEMPORARY_STORAGE, bizObjectCreated);
            //writeOperationLog(workItem.getInstanceId(), workItem.getId(), null, OperationType.TEMPORARY_STORAGE, null);
        }
        return formSave;
    }
    private void  buildFile(String workflowInstanceId) throws ParseException {
        BizObjectFacade bizObjectFacade = super.getBizObjectFacade();
        WorkflowInstanceModel wiModel = super.getWorkflowInstanceFacade().getWorkflowInstance(workflowInstanceId);
        String bizObjectId = wiModel.getBizObjectId();

        BizObjectCreatedModel bizObjectModel = super.getBizObjectFacade().getBizObject("changshangxinzeng", bizObjectId);
        SelectionValue owner = bizObjectModel.getOwner();

        //Object aa = bizObjectModel.get("Sheet1635216736286");

        /*BizObjectCreatedModel bizObject = new BizObjectCreatedModel();
        bizObject.setSchemaCode("Sheet1634872344354");*/
        List<Map<String, Object>> list = (List<Map<String, Object>>) certificate;
        for(Map<String, Object> map :list) {
            Certificate certificate = new Certificate();
            String id = UUID.randomUUID().toString().replace("-", "");
            certificate.setId(id);
            certificate.setParentid(bizObjectId);
            certificate.setCertificatename(String.valueOf(map.get("certificateName")));
            certificate.setAuthenticationscope(String.valueOf(map.get("authenticationScope")));
            certificate.setAuthenticationbody(String.valueOf(map.get("authenticationBody")));
            certificate.setDatestart(format.parse(String.valueOf(map.get("dateStart"))));
            certificate.setDateend(format.parse(String.valueOf(map.get("dateEnd"))));
            int ret = certificateMapper.insert(certificate);
            if (ret > 0 && null != map.get("file")) {
                List<Map<String, Object>> fileList = (List<Map<String, Object>>) map.get("file");
                for (Map<String, Object> file : fileList) {
                    Object responses = file.get("response");
                    String refId = "";
                    Integer fileSize = 0;
                    String mimeType = "";
                    String name = "";
                    if(null == responses){
                        refId = (String) file.get("refId");
                        fileSize = (Integer) file.get("fileSize");
                        mimeType = (String) file.get("mimeType");
                        name = (String) file.get("name");
                    }else{
                        Map<String, Object> response = (Map<String, Object>) responses;
                        Map<String, Object> data = (Map<String, Object>) response.get("data");
                        refId = (String) data.get("refId");
                        fileSize = (Integer) data.get("fileSize");
                        mimeType = (String) data.get("mimeType");
                        name = (String) data.get("name");
                    }
                    if (!StringUtils.isEmpty(refId)) {
                        BizAttachment bizAttachment = new BizAttachment();
                        bizAttachment.setId(UUID.randomUUID().toString().replace("-", ""));
                        bizAttachment.setBizobjectid(id);
                        bizAttachment.setBizpropertycode("file");
                        bizAttachment.setFilesize(fileSize);
                        bizAttachment.setMimetype(mimeType);
                        bizAttachment.setName(name);
                        bizAttachment.setParentbizobjectid(bizObjectId);
                        bizAttachment.setParentschemacode("changshangxinzeng");
                        bizAttachment.setRefid(refId);
                        bizAttachment.setSchemacode("Sheet1634872344354");
                        bizAttachment.setCreatedtime(new Date());
                        bizAttachment.setCreater(owner.getId());
                        bizAttachmentMapper.insert(bizAttachment);
                    }

                }
            }
        }
            /*Map<String, Object> data = bizObject.getData();
            data.put("parentId",bizObjectId);
            data.put("certificateName",map.get("certificateName"));
            data.put("authenticationScope",map.get("authenticationScope"));
            data.put("authenticationBody",map.get("authenticationBody"));
            data.put("name","name");
            data.put("ownerDeptQueryCode","ownerDeptQueryCode");
            data.put("sequenceNo","sequenceNo");
            data.put("sequenceStatus","sequenceStatus");
            //data.put("dateStart",map.get("dateStart"));
            //data.put("dateEnd",map.get("dateEnd"));
            String id = bizObjectFacade.saveBizObject(owner.getId(), bizObject, true);*/

    }

    public String getUserNameByErp(String userNo) {
        BizObjectQueryModel queryModel = new BizObjectQueryModel();
        queryModel.setSchemaCode("erpuser");
        queryModel.setQueryCode("erpuser");
        //queryModel.setPageable(new PageableImpl(0, 100));
        Page<BizObjectModel> modelPage = getBizObjectFacade().queryBizObjects(queryModel);

        if (modelPage != null && !CollectionUtils.isEmpty(modelPage.getContent())) {
            List<? extends BizObjectModel> content = modelPage.getContent();
            if (!CollectionUtils.isEmpty(content)) {
                for (BizObjectModel model : content) {
                    String erpUserNo = (String) model.getData().get("erpUserNo");
                    if (!StringUtils.isEmpty(erpUserNo) && erpUserNo.equals(userNo)) {
                        return (String) model.getData().get("userNo");
                    }
                }
            }
        }
        return "";
    }

    @PostMapping("/addUser")
    public ResponseResult addUser(String supplierNo,String objectId) {
        String accessToken = getDubboConfigService().getOrganizationFacade().getAccessToken("wx981c62582a466954","WECHAT" );
        log.info("accessToken={}",accessToken);
        UserModel userModel = new UserModel();
        userModel.setUsername(supplierNo);
        userModel.setName(supplierNo);
        //供应商
        userModel.setDepartmentId("2c2c80827c9e81b9017ca736dfa93803");
        userModel.setPassword("{bcrypt}$2a$10$W.rktyl4G8CYObXhPOOAJua2/WfvVvOpGVB/AW1mBIS52YUWUxV.2");
        //userModel.setDepartmentId("1803c80ed28a3e25871d58808019816e");
        userModel.setStatus(UserStatus.ENABLE);
        userModel.setUserId(supplierNo);
        userModel.setCorpId("RELEVANCE-8a96329466234db687cdb187d853798a");
        UserModel user = getOrganizationFacade().addUser(userModel);
        if(null != user){
            //添加用户与部分的关系
            addDeptUser(userModel.getDepartmentId(),user.getId());
            //获取流程的数据
            BizObjectFacade bizObjectFacade = this.getBizObjectFacade();
            //获取业务数据
            BizObjectCreatedModel bizObject = bizObjectFacade.getBizObject("changshangxinzeng", objectId);
            List<SelectionValue> list = new ArrayList<>();
            SelectionValue selectionValue = bizObject.getCreater();
            selectionValue.setType(UnitType.USER);
            selectionValue.setId(user.getId());
            selectionValue.setName(user.getName());
            list.add(selectionValue);
            bizObject.getData().put("user", list);
            bizObjectFacade.saveBizObject(bizObject.getOwner().getId(), bizObject, true);
            return getOkResponseResult(user, "新增用户成功");
        }
        return getErrResponseResult(ErrCode.UNKNOW_ERROR.getErrCode(),"新增用户失败");
    }

    //创建部门用户中间关系
    private void addDeptUser(String deptId,String userId){
        OrganizationFacade organizationFacade = this.getOrganizationFacade();
        if (StringUtils.isEmpty(deptId)||StringUtils.isEmpty(userId)){
            return;
        }
        DepartmentUserModel deptUser = organizationFacade.getDepartmentUserByDeptIdAndUserId(deptId, userId);
        if (deptUser==null){
            deptUser = new DepartmentUserModel();
        }
        deptUser.setUserId(userId);
        deptUser.setDeptId(deptId);
        organizationFacade.addDepartmentUser(deptUser);

    }
    /**
     * 附件表新增数据，使讲者协议和电子版合同产生关联
     * @param absolutePath
     * @param bizPropertyCode
     * @param schemaCode
     * @throws Exception
     */
    private int insertAttachment(String bizObjectId, String absolutePath, String bizPropertyCode, String schemaCode) throws Exception{
        // 获取下载文件
        File file = new File(absolutePath);
        log.info("获取下载的文件信息：文件名称：{}，文件大小：{}",file.getName(),file.length());
        BizAttachment bizAttachment = new BizAttachment();
        bizAttachment.setId(UUID.randomUUID().toString().replace("-",""));
        bizAttachment.setBizobjectid("id");
        bizAttachment.setBizpropertycode(bizPropertyCode);
        bizAttachment.setCreatedtime(new Date());
        bizAttachment.setCreater("creat");
        bizAttachment.setFilesize((int)file.length());
        // 获取文件的mimeType
        /*Magic parser = new Magic() ;
        MagicMatch match = parser.getMagicMatch(new File(absolutePath),false);
        bizAttachment.setMimetype(match.getMimeType());*/
        // 获取真实文件名
        bizAttachment.setName(file.getName().substring(32));
        // 获取随机生成的uuid，uuid为32位
        bizAttachment.setRefid(file.getName().substring(0,32));
        bizAttachment.setSchemacode(schemaCode);
        int result = bizAttachmentMapper.insert(bizAttachment);
        log.info("附件表插入数据，关联协议和电子版合同：{}", JSONObject.toJSONString(bizAttachment));
        if (result == 1) {
            result = 0;
        } else {
            result = (int)ErrCode.BIZ_QUERY_DATA_INVALID.getErrCode();
        }
        return result;
    }
}
